from django.shortcuts import render, redirect

import AppManager.Mysql
from AppManager import views as AMan_views
from OpManager import settings
from Logs import views as Logs_views


def getAllAuth():
    settings.UserData = {
        "UserAuthDict": {},
        "UserGroup": {}
    }
    # 查询一共多少个用户组，存进内存
    sql = "SELECT * FROM `user_gorup`"
    res = AppManager.Mysql.MysqlPool(sql, 99)
    for groupdata in res:
        settings.UserData["UserGroup"][groupdata["group"]] = {}
        for group_auth, auth in groupdata.items():
            settings.UserData["UserGroup"][groupdata["group"]][group_auth] = auth
    # 查询所有用户，存进内存
    sql = "SELECT * FROM `user`"
    res = AppManager.Mysql.MysqlPool(sql, 99)
    for users in res:
        username = users["user"]
        sql = "SELECT * FROM `user_auth` WHERE user = \"" + username + "\""
        res = AppManager.Mysql.MysqlPool(sql, 1)
        settings.UserData["UserAuthDict"][username] = {
            "Group": users["group"],
            "HostManager": res["HostManager"],
            "HostSetting": res["HostSetting"],
            "AppManager": res["AppManager"],
            "AppMonitor": res["AppMonitor"],
            "Logs": res["Logs"],
            "UserManager": res["UserManager"],
            "DomainManager": res["DomainManager"]
        }
    # print(settings.UserData)


@settings.auth(AuthType="UserManager", AuthNum=1)
def RefreshUser(requests):
    getAllAuth()
    return redirect('/user_manager')


# 新增用户
@settings.auth(AuthType="UserManager", AuthNum=1)
def AddUser(requests):
    if requests.method == 'POST':
        sql = "select * from user where user = '%s'" % (requests.POST['user'])
        res = AppManager.Mysql.MysqlPool(sql, 1)
        if res:
            print("用户 " + requests.POST['user'] + " 已存在")
        else:
            sql = "INSERT INTO `user`(`user`, `password`, `group`, `description`) VALUES " \
                  "('%s', '%s', '%s', '%s');" % (
                      requests.POST['user'], requests.POST['password'], requests.POST['group'],
                      requests.POST['description'])
            AppManager.Mysql.MysqlPool(sql, 0)
            tmpText = "用户 " + requests.POST['user'] + " 已添加," + "用户组为：" + requests.POST['group']
            print(tmpText)
            # 记录到User日志
            Logs_views.log(tmpText, "UserLog", requests.COOKIES.get('user'))

            groups = settings.UserData["UserGroup"]
            Gsql = ""
            for group in groups:
                if requests.POST['group'] in group:
                    Gsql = "INSERT INTO `user_auth`(`user`, `HostManager`, `HostSetting`, `AppManager`, " \
                           "`AppMonitor`, `Logs`, `UserManager`, `DomainManager`) VALUES " \
                           "('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');" % (requests.POST['user'], group[1],
                                                                                  group[2], group[3], group[4],
                                                                                  group[5], group[6], group[7])
            if not Gsql:
                Gsql = "INSERT INTO `user_auth`(`user`, `HostManager`, `HostSetting`, `AppManager`, `AppMonitor`, " \
                       "`Logs`, `UserManager`, `DomainManager`) VALUES" \
                       " ('%s', '000', '000', '00000', '000', '0000', '000', '00');" % (requests.POST['user'])
            print(Gsql)
            AppManager.Mysql.MysqlPool(Gsql, 0)
    getAllAuth()
    return redirect('/user_manager')


# 删除用户
@settings.auth(AuthType="UserManager", AuthNum=1)
def DelUser(requests):
    if requests.method == 'POST':
        sql = "select * from user where user = \"%s\"" % (requests.POST['user'])
        res = AppManager.Mysql.MysqlPool(sql, 1)
        # print(res)
        if res:
            sql = "DELETE FROM user WHERE user=\"%s\";" % (requests.POST['user'])
            AppManager.Mysql.MysqlPool(sql, 0)
        Logs_views.log("用户被删除：" + requests.POST['user'], "UserLog", requests.COOKIES.get('user'))
    getAllAuth()
    return redirect('/user_manager')


# 用户管理页面，可以修改用户权限
@settings.auth(AuthType="UserManager", AuthNum=1)
def UserManager(requests):
    if requests.method == 'POST':
        if requests.POST['group'] == requests.POST['oldgroup']:
            sql = "UPDATE `user_auth` SET `HostManager` = '%s', `HostSetting` = '%s', `AppManager` = '%s', " \
                  "`AppMonitor` = '%s', `Logs` = '%s', `UserManager` = '%s', `DomainManager` = '%s' WHERE " \
                  "`user` = \"%s\";" % (requests.POST['HostManager'], requests.POST['HostSetting'],
                                        requests.POST['AppManager'], requests.POST['AppMonitor'],
                                        requests.POST['Logs'], requests.POST['UserManager'],
                                        requests.POST['DomainManager'], requests.POST['user'])
            print(requests.POST['user'] + "更新了权限")
        else:
            sql = "UPDATE `opmanager`.`user` SET `group` = '%s' WHERE `user` = '%s';" \
                  "" % (requests.POST['group'], requests.POST['user'])
            AppManager.Mysql.MysqlPool(sql, 0)
            tmpText = requests.POST['user'] + "用户组从" + requests.POST['oldgroup'] + "更新为" + requests.POST[
                'group'] + "，并覆盖了权限"
            print(tmpText)
            # 记录到User日志
            Logs_views.log(tmpText, "UserLog", requests.COOKIES.get('user'))
            groups = settings.UserData["UserGroup"]
            Gsql = ""
            for group in groups:
                if requests.POST['group'] in group:
                    Gsql = "UPDATE `user_auth` SET `HostManager` = '%s', `HostSetting` = '%s', `AppManager` = '%s', " \
                           "`AppMonitor` = '%s', `Logs` = '%s', `UserManager` = '%s', `DomainManager` = '%s' WHERE " \
                           "`user` = \"%s\";" % (group[1], group[2], group[3], group[4], group[5], group[6], group[7],
                                                 requests.POST['user'])
            if not Gsql:
                Gsql = "UPDATE `user_auth` SET `HostManager` = '0', `HostSetting` = '0', `AppManager` = '0', " \
                       "`AppMonitor` = '0', `Logs` = '0', `UserManager` = '0', `DomainManager` = '0' WHERE " \
                       "`user` = \"%s\";" % (requests.POST['user'])
            sql = Gsql
            print("并覆盖了权限")
        AppManager.Mysql.MysqlPool(sql, 0)
        getAllAuth()
    context = {
        "UserAuthDict": settings.UserData["UserAuthDict"],
        "UserGroup": settings.UserData["UserGroup"]
    }
    return render(requests, "UserManager.html", context)


# 用户组管理界面
@settings.auth(AuthType="UserManager", AuthNum=2)
def UsersManager(requests):
    if requests.method == 'POST':
        sql = "UPDATE `user_gorup` SET `HostManager`='%s', `HostSetting`='%s', `AppManager`='%s'," \
              " `AppMonitor`='%s', `Logs`='%s', `UserManager`='%s', `DomainManager`='%s' WHERE `group`='%s';" % (
                  requests.POST['HostManager'], requests.POST['HostSetting'],
                  requests.POST['AppManager'], requests.POST['AppMonitor'],
                  requests.POST['Logs'], requests.POST['UserManager'],
                  requests.POST['DomainManager'], requests.POST['group'])
        AppManager.Mysql.MysqlPool(sql, 0)
        # 记录到日志中
        tmpText = "用户组：" + requests.POST['group'] + "修改了权限。"
        Logs_views.log(tmpText, "UserLog", requests.COOKIES.get('user'))

        getAllAuth()
    context = {
        "UserGroup": settings.UserData["UserGroup"]
    }
    print(context)
    return render(requests, "UserGroupsManager.html", context)


# 刷新用户权限
@settings.auth(AuthType="UserManager", AuthNum=2)
def RefreshGroup(requests):
    getAllAuth()
    return redirect('/users_manager')


# 添加用户组
@settings.auth(AuthType="UserManager", AuthNum=2)
def AddGroup(requests):
    if requests.method == 'POST':
        tmpTuple = (requests.POST['group'], requests.POST['HostManager'], requests.POST['HostSetting'],
                    requests.POST['AppManager'], requests.POST['AppMonitor'],
                    requests.POST['Logs'], requests.POST['UserManager'],
                    requests.POST['DomainManager'])
        sql = "INSERT INTO `user_gorup`(`group`, `HostManager`, `HostSetting`, `AppManager`," \
              " `AppMonitor`, `Logs`, `UserManager`, `DomainManager`) VALUES " \
              "('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');" % tmpTuple
        AppManager.Mysql.MysqlPool(sql, 0)
        # 记录到日志中
        tmpText = "新增用户组：%s,权限：HostManager：=%s,HostSetting：=%s,AppManager：=%s," \
                  "AppMonitor：=%s,Logs：=%s,UserManager：=%s,DomainManager：=%s" % tmpTuple
        print(tmpText)
        Logs_views.log(tmpText, "UserLog", requests.COOKIES.get('user'))

        getAllAuth()
    return redirect('/users_manager')


@settings.auth(AuthType="UserManager", AuthNum=2)
def DelGroup(requests):
    if requests.method == 'POST':
        sql = "select * from user_gorup where `group` = \"%s\"" % (requests.POST['group'])
        res = AppManager.Mysql.MysqlPool(sql, 1)
        if res:
            sql = "DELETE FROM user_gorup WHERE `group` = \"%s\";" % (requests.POST['group'])
            AppManager.Mysql.MysqlPool(sql, 0)

            tmpText = "用户组：" + requests.POST['group'] + " 已删除"
            print(tmpText)
            Logs_views.log(tmpText, "UserLog", requests.COOKIES.get('user'))

    getAllAuth()
    return redirect('/users_manager')


@settings.auth(AuthType="UserManager", AuthNum=3)
def UserSetting(requests):
    user = requests.COOKIES.get('user')
    User = {}
    sql = "SELECT * FROM `user` WHERE `user` = '%s'" % user
    res = AppManager.Mysql.MysqlPool(sql, 1)
    if res:
        User = {
            "user": user,
            "group": res["group"],
            "description": res["description"]
        }
    if requests.method == 'POST':
        if requests.POST["password"]:
            sql = "UPDATE `user` SET `password` = '%s', `description` = '%s' " \
                  "WHERE  `user` = '%s';" % (requests.POST["password"], requests.POST["description"], user)
            AppManager.Mysql.MysqlPool(sql, 0)
            Logs_views.log("用户更改了密码", "UserLog", requests.COOKIES.get('user'))
            return redirect('/logout')
        else:
            sql = "UPDATE `user` SET `description` = '%s' WHERE  `user` = '%s';" % (requests.POST["description"], user)
            AppManager.Mysql.MysqlPool(sql, 0)
            return redirect('/user_setting')
    context = {
        "User": User
    }
    return render(requests, "UserSetting.html", context)


getAllAuth()
